package com.concurrent.sample.business.manager.impl;

import com.concurrent.sample.business.consts.enums.FlowTypeEnum;
import com.concurrent.sample.business.entity.EventEntity;
import com.concurrent.sample.business.entity.OrderEntity;
import com.concurrent.sample.business.consts.enums.EventTypeEnum;
import com.concurrent.sample.business.consts.enums.SideEnum;
import com.concurrent.sample.business.consts.enums.TargetStatusEnum;
import com.concurrent.sample.business.dto.param.PositionUpdateQtyParam;
import com.concurrent.sample.business.dto.report.TradeExecReportDTO;
import com.concurrent.sample.business.dto.trade.CreateTradeEventParamParam;
import com.concurrent.sample.business.dto.trade.TradeExecReportParamParam;
import com.concurrent.sample.business.service.EventService;
import com.concurrent.sample.business.service.OrderService;
import com.concurrent.sample.business.service.PositionService;
import java.util.Collections;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
@Slf4j
public class TradeEventShortClosingServiceImpl extends AbstractTradeEventService {

  private final EventService eventService;

  private final OrderService orderService;

  private final PositionService positionService;

  @Override
  public EventTypeEnum getEventType() {
    return EventTypeEnum.TRADE_SHORT;
  }

  @Override
  public SideEnum getSide() {
    return SideEnum.BUY;
  }

  @Override
  public void enableTrade(CreateTradeEventParamParam tradeEventParam) {
  }

  @Override
  public void beforeHandleTrade(CreateTradeEventParamParam createTradeEventParam) {
    super.beforeHandleTrade(createTradeEventParam);
    EventEntity eventEntity = createTradeEventParam.getEvent();
    Long orderQty = eventEntity.getQuantity();
    // 扣除当日可买数量、空头存续数量
    positionService.updateQty(new PositionUpdateQtyParam()
        .setPositionId(eventEntity.getPositionId())
        .setAvailableBuyQty(orderQty)
        .setLeaveShortQty(orderQty)
    );

    // 自动确认审批状态
    OrderEntity orderEntity = createTradeEventParam.getOrder();
    orderEntity.setFlowStatus(FlowTypeEnum.CONFIRMED);
    orderService.save(Collections.singletonList(orderEntity));
  }

  @Override
  public void handlingTradeExecReport(TradeExecReportParamParam tradeExecReportParam) {
    EventEntity event = tradeExecReportParam.getEvent();
    TradeExecReportDTO execReport = tradeExecReportParam.getExecReport();
    Long quantity = execReport.getQuantity();

    // 持仓更新
    if(quantity > 0){
      // 买完后加可还、可买、当日买入数量
      positionService.updateQty(new PositionUpdateQtyParam()
          .setPositionId(event.getPositionId())
          .setIntradayBuyQty(-quantity)
          .setReturnableQty(-quantity)
      );
    }

    // 事件更新
    event.setInitPrice(execReport.getExecPrice())
        .setTargetStatus(TargetStatusEnum.SUCCESS);

    eventService.save(Collections.singletonList(event));
  }
}
